package com.group4.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.group4.edu.client.VodClient;
import com.group4.edu.entity.Video;
import com.group4.edu.mapper.VideoMapper;
import com.group4.edu.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.study.exceptions.VideoException;
import com.study.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author cloud
 * @since 2022-03-10
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VodClient vodClient;

    @Override
    public void deleteVideoByCourseId(String courseId) {
        QueryWrapper<Video> qw = new QueryWrapper<>();
        qw.eq("course_id", courseId);

        List<Video> videos = baseMapper.selectList(qw);
        if (videos.size() == 0) {
            throw new VideoException("课程不存在或该课程没有小节");
        }
        Set<String> ids = new HashSet<>();
        videos.forEach(v -> {
            if (!StringUtils.isNullOrEmpty(v.getVideoSourceId())) {
                ids.add(v.getVideoSourceId());
            }
        });

        if (ids.size() == 0) {
            throw new VideoException("该课程没有视频");
        }
        ResponseResult<Void> result = vodClient.removeVideoList(ids);
        if (result.getCode() != 200) {
            throw new VideoException(result.getMessage());
        }
        int rows = baseMapper.delete(qw);
        if (rows <= 0) {
            throw new VideoException("刪除视频失败");
        }
    }
}
